package handlers

import (
	"bytes"
	"fmt"
	"generalhandler/conf"
	"github.com/nsqio/go-nsq"
	"os"
	"time"
)

type BaseMQHandler struct {
	producer *nsq.Producer
}

func (bmqh *BaseMQHandler) Init() error {
	var err error
	bmqh.producer, err = nsq.NewProducer(conf.MQConfigInstance().NsqdTcpAddresses[0], nsq.NewConfig())
	if nil != err {
		return fmt.Errorf("failed to nsq.NewProducer, cuz %s", err.Error())
	}

	return nil
}

func (bmqh *BaseMQHandler) handleMessage(bytesMsg []byte) error {
	panic("no impl")
}

func (bmqh *BaseMQHandler) PublishMessage(topic string, msg []byte) {
	for {
		err := bmqh.producer.Publish(topic, msg)
		if nil == err {
			break
		}
		fmt.Fprint(os.Stderr,
			fmt.Sprintf("failed to pushlish msg to %s, cuz %s, trying later.", topic, err.Error()))
		time.Sleep(5 * time.Second)
	}
}

func (bmqh *BaseMQHandler) PublishLog(log []byte) {
	//fmt.Println(string(log))
	bmqh.PublishMessage(conf.MQConfigInstance().LogTopic, log)
}

var hostName, vprefix, iprefix, wprefix, eprefix string
var pid int

func init() {
	var err error
	hostName, err = os.Hostname()
	if nil != err {
		panic(fmt.Sprintf("failed to get hostname, cuz %s", err.Error()))
	}
	pid = os.Getpid()
	vprefix = fmt.Sprintf("[v|%s|%d] ", hostName, pid)
	iprefix = fmt.Sprintf("[i|%s|%d] ", hostName, pid)
	wprefix = fmt.Sprintf("[w|%s|%d] ", hostName, pid)
	eprefix = fmt.Sprintf("[e|%s|%d] ", hostName, pid)
}

func (bmqh *BaseMQHandler) log(logPrefix string, format string, a ...interface{}) {
	var buf bytes.Buffer
	buf.WriteString(logPrefix)
	buf.WriteString(fmt.Sprintf("%s|%d> ", conf.MQConfigInstance().HandlerName, time.Now().Unix()))
	buf.WriteString(fmt.Sprintf(format, a...))
	bmqh.PublishLog(buf.Bytes())
}

func (bmqh *BaseMQHandler) Verb(format string, a ...interface{}) {
	bmqh.log(vprefix, format, a...)
}

func (bmqh *BaseMQHandler) Info(format string, a ...interface{}) {
	bmqh.log(iprefix, format, a...)
}

func (bmqh *BaseMQHandler) Warn(format string, a ...interface{}) {
	bmqh.log(wprefix, format, a...)
}

func (bmqh *BaseMQHandler) Error(format string, a ...interface{}) {
	bmqh.log(eprefix, format, a...)
}
